package jupiter.node;

import jupiter.message.Message;
import java.util.ArrayList;
import org.json.*;
import java.util.UUID;
/**
 * Basically adds and removes itself from DomainNode
 * @author Justin
 *
 */
public class AddressableNode extends Node {
	
	private ArrayList<Address> blocks = new ArrayList<Address>();
	private ArrayList<Address> only= new ArrayList<Address>();
	private ArrayList<Address> nodes= new ArrayList<Address>();
	
	protected UUID uuid;
	
	public AddressableNode( Address a, SessionNode creator) {
		super(a);
		
		//check domain rules
		
	}
	/**
	 * Creates a node from a message like:
	 * 
	 * {
	 *	  type: "node"
	 *	  action: "create"
	 *	  from: "jmvc.com@jabbify.com"
	 *	  to: "justin#jmvc.com@jabbify.com"
	 *	  data : {
	 *	    nodes: ['#jmvc.com@jabbify.com'] //which nodes I subscribe to
	 *	  }
	 * }
	 * @param m
	 */
	public AddressableNode( Message m) {
		super(m.to());
		
		//need to validate making this node is ok
		
		loadIntoArray(m.data,"blocks", blocks);
		loadIntoArray(m.data,"only", only);
		loadIntoArray(m.data,"nodes", nodes);
		
		//attach listeners
		//DomainNode d = GlobalNode.getDomain(m.to());
		for(Address a : nodes){
			listenTo(a);
		}
		
		//DomainNode d = DomainNode.getDomain(m.to);
		//d.addDirectListener(this);
		
		//load rules from domain
	}

	private void loadIntoArray(JSONObject d, String type, ArrayList<Address> list){
		try{
			if(d.has(type)){
				JSONArray arr = d.getJSONArray(type);
				int l = arr.length();
				for(int i = 0; i < l; i++){
					list.add( new Address( arr.getString(i)  ));
				}
			}
		}catch(JSONException e){	
			
		}
	}
	

	public JSONObject sendMessage(Message m){
		//check to make sure from isn't blocked
		if(isBlocked(m)) return null;
		return super.sendMessage(m);
		
	}
	
	public boolean isBlocked(Message m){
		return false;
	}
}
